package com.ruoyi.framework.web.service;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.CsoftSecurityUtil;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.auth2.AccessToken;
import com.ruoyi.framework.auth2.Auth2ContextHolder;
import com.ruoyi.framework.auth2.OAuth2Authentication;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService {
	@Autowired
	private TokenService tokenService;
	@Autowired
	private OAuth2Authentication oauth2;

	@Resource
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisCache redisCache;

	/**
	 * 登录验证
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param code
	 *            验证码
	 * @param uuid
	 *            唯一标识
	 * @return 结果
	 */
	public String login(String username, String password, String code, String uuid) {
		if ("weixinCode".equals(code)){
			Auth2ContextHolder.setSSO(true);
			password = "ssologin";
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			// 用户验证
			Authentication authentication2 = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(username, password));
			AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS,
					MessageUtils.message("user.login.success")));
			LoginUser loginUser = (LoginUser) authentication2.getPrincipal();
			SecurityContextHolder.getContext().setAuthentication(authentication2);
			// 生成token
			return tokenService.createToken(loginUser);
		}
		boolean ssoLogin = username==null;
		AccessToken accessToken = null;
		if(!ssoLogin){
			String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
			String captcha = redisCache.getCacheObject(verifyKey);
	
			if (captcha == null) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
						MessageUtils.message("user.jcaptcha.expire")));
				throw new CaptchaExpireException();
			}
			redisCache.deleteObject(verifyKey);
			if (!code.equalsIgnoreCase(captcha)) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
						MessageUtils.message("user.jcaptcha.error")));
				throw new CaptchaException();
			}
			try {
				password = CsoftSecurityUtil.decryptRSADefault(CsoftSecurityUtil.privateKey, password);
			} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException
					| IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new RuntimeException("用户登录密码解密失败.");
			}
			Auth2ContextHolder.setSSO(false);
		}else{
			if(code==null){
				throw new RuntimeException("没有获取到Auth2登录所需的code值,请确认登录之前已经访问Auth2服务器.");
			}
			password = "ssologin";
			accessToken = oauth2.getAccessToken(code);
			if(accessToken==null){
				throw new RuntimeException("通过code未获取Auth2服务器的access-token值.");
			}
			username = oauth2.getUserId(accessToken.getName());
			if(username==null){
				throw new RuntimeException("获取Auth2服务器当前用户ID失败.");
			}
			Auth2ContextHolder.setSSO(true);
		}
		// 用户验证
		Authentication authentication = null;
		try {

			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
						MessageUtils.message("user.password.not.match")));
				throw new UserPasswordNotMatchException();
			} else {
				AsyncManager.me()
						.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
				throw new CustomException(e.getMessage());
			}
		}
		AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS,
				MessageUtils.message("user.login.success")));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		SecurityContextHolder.getContext().setAuthentication(authentication);
		/*if(ssoLogin){
			return accessToken.getName();
		}*/
		// 生成token
		return tokenService.createToken(loginUser);
	}
}
